<template>
	<view class="nt-upload" :class="{ hidden: mode === 'preview', loading: loading }">
		<!-- <nt-image-upload
		 :max="3"  
		 v-model="test" 
		 :uploadSuccess="zidingyiSuccess"
		></nt-image-upload> -->
		<nt-image-compress ref="imageCompress"></nt-image-compress>
		<u-upload :fileList="priveImage" @afterRead="afterRead" @delete="deletePic" name="file" :maxCount="maxCount"
			previewFullImage multiple accept="image" :deletable="mode === 'upload'" :disabled="mode === 'preview'"
			:sizeType="['compressed']"></u-upload>
		<!-- <view class="nt-upload__item">
			<u-upload></u-upload>
		</view> -->
		<u-loading-page :loading="loading" loadingText="上传中..." bgColor="rgba(0,0,0,0.5)"></u-loading-page>
	</view>
</template>

<script>
	import {
		appConfig
	} from "@/config"
	import {
		uploadFile
	} from "@/utils/request"
	import Compressor from 'compressorjs'
	// import ImageUpload from "@/components/image-upload/index.vue"
	const URL = appConfig.BASE_URL + "order/upload"
	export default {
		props: {
			maxCount: {
				type: Number,
				default: 3
			},
			images: {
				type: Array,
				default: () => []
			},
			// preview
			mode: {
				type: String,
				default: "upload"
			}
		},
		data() {
			return {
				test: [],
				fileList: [],
				// 预览
				priveImage: [],
				loading: false,
				// 方式进入监听死循环
				count: 0
			}
		},
		watch: {
			fileList: {
				handler(nv) {
					// if(nv.length === 0) return;
					this.priveImage = nv.map(item => {
						let data = {
							...item
						}
						data.url = (appConfig.imgCDN + item.url).replace(/\\/g, "/")
						return data;
					})
				},
				deep: true,
				immediate: true
			},
			images: {
				handler(nv) {
					if (this.count > 0) return;
					if (Array.isArray(nv) && nv.length > 0) {
						this.fileList = nv.map(item => {
							return {
								url: item
							}
						})
						this.count++
						this.$emit("success", this.fileList)
					}
				},
				immediate: true
			}
		},
		methods: {
			zidingyiSuccess(e) {
				console.log(e, '成功')
			},
			async afterRead(event) {
				let URL = event.file[0].url.startsWith('file://')
				if (!URL) {
					uni.saveImageToPhotosAlbum({
						filePath: event.file[0].url
					})
				}
				for (let i = 0; i < event.file.length; i++) {
					await this.uploadFilePromise(event.file[i])
				}
				// this.loading = true
				// this.uploadFilePromise(event.file[0])
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				// let lists = [].concat(event.file)
				// let fileListLen = this[`fileList${event.name}`].length
				// lists.map((item) => {
				// 	this[`fileList${event.name}`].push({
				// 		...item,
				// 		status: 'uploading',
				// 		message: '上传中'
				// 	})
				// })
				// for (let i = 0; i < lists.length; i++) {
				// 	const result = await this.uploadFilePromise(lists[i].url)
				// 	let item = this[`fileList${event.name}`][fileListLen]
				// 	this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
				// 		status: 'success',
				// 		message: '',
				// 		url: result
				// 	}))
				// 	fileListLen++
				// }
			},
			deletePic(e) {
				let index = e.index
				this.fileList.splice(index, 1)
				this.count = 0
				this.$emit("success", this.fileList)
			},
			async uploadFilePromise(file) {
				const parmas = {
					url: URL,
					filePath: file.url
				}
				// 大于2M压缩图片
				if (file.size > 2 * 1024 * 1024) {
					// 压缩图片
					const compressResult = await this.compressImage(file.file)
					if (!compressResult) return this.toast("图片压缩失败")
					parmas.filePath = compressResult
				}
				uploadFile(parmas).then(res => {
					const {
						code,
						msg,
						data
					} = JSON.parse(res) || {};
					if (code === 1) {
						this.toast(msg)
						this.$set(this.fileList, this.fileList.length, {
							url: data.url
						})
						this.$emit("success", this.fileList)
					}
				}).catch(err => {
					this.toast("上传失败")
				}).finally(err => {
					this.loading = false
				})
			},
			compressImage(file) {
				return new Promise((resolve, reject) => {
					this.$refs.imageCompress.compress({
						src: file.path,
						maxSize: 1080,
						fileType: 'jpg',
						quality: 0.9,
						minSize: 640 //最小压缩尺寸，图片尺寸小于该时值不压缩，非H5平台有效。若需要忽略该设置，可设置为一个极小的值，比如负数。
					}).then((res) => {
						resolve(res)
						// 压缩成功回调
					}).catch((err) => {
						// 压缩失败回调
					})

					// 批量压缩
					/* this.$refs.helangCompress.compress({
					    src:this.paths,
					    maxSize:800,
					    fileType:'jpg',
					    quality:0.85,
					    progress:(res)=>{
					        console.log('压缩进度');
					        console.log(res);
					    }
					}).then((res)=>{
					    // 压缩成功回调
					}).catch((err)=>{
					    // 压缩成功回调
					}) */
				})
				/* return new Promise((resolve, reject) => {
					// 需要改动uview upload源码，否则无法使用压缩插件
					new Compressor(file, {
					  quality: 0.6, //图片压缩比例，取值范围为0~1
					  success(result) {
						  // resolve(result)
						  const res = new File([result], file.name, { type: result.type, lastModified: Date.now() })
						  console.log(result, '压缩成功', res)
						  resolve(result)
					  },
					  error(err) {
					    console.log(err.message, '压缩失败')
						reject(false)
					  }
					})
				}) */
			}
		}
	}
</script>

<style lang="scss" scoped>
	.nt-upload {
		&.loading {
			position: relative;
			z-index: 10;
		}

		&.hidden {
			/deep/.u-upload__button {
				display: none;
			}

		}

		// display: grid;
		// grid-template-columns: repeat(3, 30%);
		// grid-column-gap: 5%;
		// grid-row-gap: 20rpx;
	}
</style>